// pages/mine/editInfo/editInfo.js
const app = getApp()
import {
  request
} from '../../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight1: app.globalData.statusBarHeight + 45,
    userName: '',
    idNumber: '',
    phone: '',
    addr: '',
    // 是否低于37   1  是  2 否    
    radio: '1',
    // 乘车位置
    rideBusAddr: {},
    // 用户id
    userId: '',
    // sessionkey 和openid
    codeData: '',
    // 省市区选择
    region: ['省', '市', '区/县'],
    // 户籍地详情
    desc: '',
    // 定位的经纬度
    long: '',
    byLat: '',
    // 车牌号
    carNumber: '',
    // 显示填写表单
    showForm: false,
    // 显示提示信息
    showTrip: false,
    // 需要保存的用户信息  昵称 头像 电话 
    saveUserInfo: {},
    // 显示获取用户信息按钮
    showUser: true,
    // 显示获取用户手机按钮
    showPhone: false
  },
  goBack() {
    wx.navigateBack({
      delta: 1,
    })
  },
  // 温度变化表
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  // 省市区变化
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  // 提交 表单
  onSubmit() {
    if (!this.data.userName.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }
    if (!this.data.idNumber.trim()) {
      wx.showToast({
        title: '请输入身份证号',
        icon: 'none'
      })
      return
    }
    if (!this.data.phone.trim()) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }
    if (this.data.region[0] == '省') {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return
    }
    if (!this.data.desc.trim()) {
      wx.showToast({
        title: '请输入户籍地址详情',
        icon: 'none'
      })
      return
    }
    request({
      url: '/passengerTraffic-applet/applet/diseasePrevent/saveDiseasePrevent',
      method: 'post',
      data: {
        userId: this.data.userId,
        realName: this.data.userName,
        idNumber: this.data.idNumber,
        realPhone: this.data.phone,
        addrProvince: this.data.region[0],
        addrCity: this.data.region[1],
        addrCountry: this.data.region[2],
        addrDesc: this.data.desc,
        animalHeat: this.data.radio == 1 ? '是' : '否',
        byLong: this.data.long,
        byLat: this.data.lat,
        carNumber: this.data.carNumber
      }
    }).then(res => {
      console.log(res);
      if (res.code == 1) {
        wx.showToast({
          title: '提交成功'
        })
        this.setData({
          showForm: false,
          showTrip: true
        })
      }
    })
  },
  // 获取扫码结果
  onSubCode() {
    request({
      url: '/passengerTraffic-applet/applet/diseasePrevent/selectUserDiseasePrevent',
      method: 'post',
      data: {
        carNumber: this.data.carNumber,
        userId: this.data.userId
      }
    }).then(res => {
      console.log('扫码结果', res);
      // 没有填写过
      if (res.code == 1 && res.data.fillState == 0) {
        this.setData({
          showForm: true
        })
      }
      if (res.code == 1 && res.data.fillState == 1) {
        this.setData({
          showForm: true,
          userName: res.data.realName,
          idNumber: res.data.idNumber,
          phone: res.data.realPhone,
          desc: res.data.addrProvince,
          region: [res.data.addrProvince + '', res.data.addrCity + '', res.data.addrCountry + '']
        })
      }
    })
  },
  // 返回首页
  goIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  // 解码车牌
  jiema(scene) {
    request({
      url: '/passengerTraffic-applet/applet/diseasePrevent/getCarNumber',
      method: 'post',
      data: {
        scene
      }
    }).then(res => {
      if (res.code == 1) {
        this.setData({
          carNumber: res.data.carNumber
        })
      }
    })
  },
  // 获取用户头像 昵称
  bindGetUserInfo(e) {
    console.log('用户信息', e);
    if (e.detail.iv) {
      this.setData({
        showPhone: true,
        showUser: false,
        saveUserInfo: {
          username: e.detail.userInfo.nickName,
          headimg: e.detail.userInfo.avatarUrl
        }
      })
    }
    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      wx.showToast({
        title: '拒绝将无法填写申报健康信息！！',
        duration: 2500,
        icon: 'none'
      })
      return
    }
  },
  // 授权手机号
  bindGetPhone(e) {
    console.log(e);
    if (e.detail.iv) {
      // 向后台换取手机号
      request({
        url: '/passengerTraffic-applet/applet/user/deciphering',
        method: 'POST',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          session_key: this.data.codeData.session_key
        }
      }).then(res1 => {
        console.log(res1);
        this.setData({
          saveUserInfo: {
            ...this.data.saveUserInfo,
            phone: res1.phoneNumber,
            openid: this.data.codeData.openid
          },
          showForm: true,
          showPhone: false
        })
        //查询userid  如果新用户  查不到信息  此时 先存 然后再查  拿userId
        request({
          url: '/passengerTraffic-applet/applet/user/selUserByOpenId',
          method: 'POST',
          data: {
            openId: this.data.codeData.openid
          }
        }).then(res3 => {
          if (res3.code == 1) {
            this.setData({
              userId: res3.data.id
            })
            this.onSubCode()
          } else {
            // 发送后台保存用户信息
            request({
              url: '/passengerTraffic-applet/applet/user/saveUser',
              method: 'POST',
              data: this.data.saveUserInfo
            }).then(res2 => {
              // console.log(res2);
                //查询userid 
                request({
                  url: '/passengerTraffic-applet/applet/user/selUserByOpenId',
                  method: 'POST',
                  data: {
                    openId: this.data.codeData.openid
                  }
                }).then(res => {
                  if(res.code == 1) {
                    this.setData({
                      userId: res.data.id
                    })
                  }
                })
            })
          }
        })

      })

    }
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showToast({
        title: '拒绝将无法填写申报健康信息！！',
        duration: 2500,
        icon: 'none'
      })
      return
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取扫描小程序码进来的参数
    const scene = decodeURIComponent(options.scene)
    console.log(scene);
    if (scene) {
      // let carNumber = scene.split('=')
      this.jiema(scene)
    }
    // 获取用户当前位置
    wx.getLocation({
      type: 'gcj02',
      success: res => {
        console.log('定位', res);
        this.setData({
          long: res.longitude,
          lat: res.latitude
        })
      }
    })
    // 获取userId
    wx.getStorage({
      key: 'userId',
      success: res => {
        this.setData({
          userId: res.data,
          showUser: false
        })
        this.onSubCode()
      },
      fail: res => {
        console.log('失败', res);
        // 登录
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            request({
              url: '/passengerTraffic-applet/applet/user/getappid',
              method: 'POST',
              data: {
                code: res.code
              }
            }).then(res1 => {
              console.log(res1);
              let codeData = {}
              codeData.openid = res1.data.openid
              codeData.session_key = res1.data.session_key
              this.setData({
                codeData: codeData
              })
            })
          }
        })

      }
    })
  },




  // request({
  //   url: '/passengerTraffic-applet/applet/user/selUserByOpenId',
  //   method: 'POST',
  //   data: {
  //     openId: openid
  //   }
  // }).then(res3 => {
  //   if (res3.code == 1) {
  //     this.setData({
  //       userId: res3.data.id,
  //     })
  //     this.onSubCode()
  //   }
  // })
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})